#pragma once
#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <functional>
#include <string>
using namespace std;

template <class T>
using func_t = std::function<void(T)>;


namespace zhong
{
    // 类模块
    template <class T>
    class Thread
    {
    public:
        // 默认函数
        Thread(const string &thread_name, func_t<T> func, T data)
            : _tid(0), _thread_name(thread_name), _func(func), _isrunning(false), _data(data)
        {
        }
        ~Thread() {}

        // 禁用this指针
        static void *TreadFunc(void *args)
        {
            Thread *t = (Thread *)args;
            t->_func(t->_data);

            return nullptr;
        }

        bool Start()
        {
            // 调用pthread_create，传入参数为：对象this
            int n = pthread_create(&_tid, nullptr, TreadFunc, this);
            if (n == 0)
            {
                _isrunning = true;
                return true;
            }
            else
            {
                return false;
            }
        }

        bool Join()
        {
            if (IsRunning() == false)
                return false;
            int n = pthread_join(_tid, nullptr);
            if (n == 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        bool IsRunning() const
        {
            return _isrunning;
        }

        string GetThreadName() const
        {
            return _thread_name;
        }

    private:
        pthread_t _tid;
        string _thread_name;
        func_t<T> _func;
        bool _isrunning;
        T _data;
    };

    // 函数模块
    string GetThreadName()
    {
        static int i = 1;
        char name[64];
        snprintf(name, sizeof(name), "Thread-%d", i++);
        return name;
    }

}